<template>
    <div class="detail-container">
        <el-card class="detail-card" shadow="never">
            <!-- 顶部标题和操作区域 -->
            <div class="header-section">
                <div class="title-area">
                    <h2 class="title">
                        {{ info.supplierName || '-' }}（{{ info.supplierCode || '--' }}）
                    </h2>
                    <el-icon @click="handleCopy" class="copy-icon" title="复制">
                        <DocumentCopy />
                    </el-icon>
                </div>
                <div class="action-area">
                    <div class="status-info">
                        <span class="status-label">状态</span>
                        <el-tag v-if="String(info.supplierStatus) === '0'" type="success" size="large">启用</el-tag>
                        <el-tag v-else-if="String(info.supplierStatus) === '1'" type="danger" size="large">禁用</el-tag>
                        <span v-else>-</span>
                    </div>
                    <div class="action-buttons">
                        <el-button type="primary" @click="handleEdit">编辑</el-button>
                        <el-button type="danger" @click="handleDelete">删除</el-button>
                        <el-button type="warning" @click="handleDisable">停用</el-button>
                        <el-button @click="handlePrint">打印</el-button>
                    </div>
                </div>
            </div>

            <!-- 供应商基本信息 -->
            <div class="info-card">
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="所属行业">
                        <span class="info-value">{{ info.industryName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="供应商分类">
                        <span class="info-value">{{ info.supplierTypeName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="联系人">
                        <span class="info-value">{{ info.contact || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="供应商状态">
                        <el-tag v-if="String(info.supplierStatus) === '0'" type="success">启用</el-tag>
                        <el-tag v-else-if="String(info.supplierStatus) === '1'" type="danger">禁用</el-tag>
                        <span v-else>-</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="联系电话">
                        <span class="info-value">{{ info.contactNumber || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="电子邮箱">
                        <span class="info-value">{{ info.supplierEmail || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="进货部门">
                        <span class="info-value">{{ info.organizationName || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="进货负责人">
                        <span class="info-value">{{ info.userName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="供应商地址" :span="2">
                        <span class="info-value">{{ info.supplierAddress || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="1" border class="info-row">
                    <el-descriptions-item label="备注">
                        <span class="info-value">{{ info.remarks || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <!-- 审核信息 -->
                <el-descriptions :column="4" border class="audit-row">
                    <el-descriptions-item label="创建人">
                        <span class="info-value">{{ info.createor || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                        <span class="info-value">{{ formatDate(info.createrTime) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="更新人">
                        <span class="info-value">{{ info.updator || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="更新时间">
                        <span class="info-value">{{ formatDate(info.updateTime) }}</span>
                    </el-descriptions-item>
                </el-descriptions>
                
            </div>

            <!-- 标签页区域 -->
            <div class="tabs-section">
                <el-tabs v-model="activeTab" type="card" class="detail-tabs">
                    <!-- 其他信息标签页 -->
                    <el-tab-pane label="其他信息" name="other">
                        <div class="tab-content">
                            <!-- 财务信息 -->
                            <div class="section-block">
                                <h3 class="section-title">财务信息</h3>
                                <el-descriptions :column="2" border>
                                    <el-descriptions-item label="账户名称">
                                        <span class="info-value">{{ info.financeName || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="纳税人识别号">
                                        <span class="info-value">{{ info.taxpayerNumber || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="银行账户">
                                        <span class="info-value">{{ info.bankAccount || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="开户银行">
                                        <span class="info-value">{{ info.accountBank || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="开户行地址" :span="2">
                                        <span class="info-value">{{ info.bankAddress || '-' }}</span>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>

                            <!-- 附件 -->
                            <div class="section-block">
                                <h3 class="section-title">附件</h3>
                                <div class="attachment-list">
                                    <el-link
                                        v-for="(file, index) in attachments"
                                        :key="index"
                                        :href="file.url"
                                        :underline="false"
                                        type="primary"
                                        class="file-link"
                                        target="_blank"
                                    >
                                        📎 {{ file.name }}
                                    </el-link>
                                    <div v-if="attachments.length === 0" class="empty-text">暂无附件</div>
                                </div>
                            </div>

                            <!-- 自定义字段 -->
                            <div class="section-block">
                                <h3 class="section-title">自定义字段</h3>
                                <div v-if="customFields.filter(f => f.value).length === 0" class="empty-text">
                                    暂无自定义字段
                                </div>
                                <el-descriptions v-else :column="2" border>
                                    <el-descriptions-item
                                        v-for="(field, index) in customFields.filter(f => f.value)"
                                        :key="index"
                                        :label="field.label"
                                    >
                                        <span class="info-value">{{ field.value }}</span>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 进货记录标签页 -->
                    <el-tab-pane label="进货记录" name="purchase">
                        <div class="tab-content">
                            <el-table
                                v-loading="purchaseLoading"
                                :data="purchaseRecords"
                                border
                                stripe
                                v-if="purchaseRecords.length"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="stockinGoodsNo" label="进货单号" min-width="160" />
                                <el-table-column label="单据状态" width="110">
                                    <template #default="{ row }">
                                        <el-tag :type="getPurchaseStatusTag(row.stockinGoodsStatus)" size="small">
                                            {{ getPurchaseStatusText(row.stockinGoodsStatus) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="stockinGoodsDate" label="进货日期" width="130">
                                    <template #default="{ row }">
                                        {{ formatDate(row.stockinGoodsDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="organizationName" label="进货部门" min-width="150" />
                                <el-table-column prop="userName" label="经办人" width="120" />
                                <el-table-column prop="stockinGoodsCount" label="进货数量" width="110" align="right" />
                                <el-table-column label="进货金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.stockinGoodsAmount) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
                            </el-table>
                            <el-empty
                                v-else-if="!purchaseLoading"
                                description="暂无进货记录"
                            />
                        </div>
                    </el-tab-pane>

                    <!-- 出库记录标签页 -->
                    <el-tab-pane label="出库记录" name="outbound">
                        <div class="tab-content">
                            <el-table
                                v-loading="outboundLoading"
                                :data="outboundRecords"
                                border
                                stripe
                                v-if="outboundRecords.length"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="goodsReturnsNo" label="退货单号" min-width="160" />
                                <el-table-column label="状态" width="110">
                                    <template #default="{ row }">
                                        <el-tag :type="getReturnStatusTag(row.goodsReturnsStatus)" size="small">
                                            {{ getReturnStatusText(row.goodsReturnsStatus) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goodsReturnsDate" label="退货日期" width="130">
                                    <template #default="{ row }">
                                        {{ formatDate(row.goodsReturnsDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goodsReturnsUser" label="退货人" width="120" />
                                <el-table-column prop="goodsReturnsQuantity" label="退货数量" width="110" align="right" />
                                <el-table-column label="退货金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.goodsReturnsAmount) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goodsReturnsReason" label="退货原因" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <el-empty
                                v-else-if="!outboundLoading"
                                description="暂无出库记录"
                            />
                        </div>
                    </el-tab-pane>

                    <!-- 入库记录标签页 -->
                    <el-tab-pane label="入库记录" name="inbound">
                        <div class="tab-content">
                            <el-table
                                v-loading="inboundLoading"
                                :data="inboundRecords"
                                border
                                stripe
                                v-if="inboundRecords.length"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="warehousingCode" label="入库单号" min-width="160" />
                                <el-table-column prop="warehousingTypeName" label="入库类型" width="120" />
                                <el-table-column prop="storageDate" label="入库日期" width="130">
                                    <template #default="{ row }">
                                        {{ formatDate(row.storageDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="warehouseName" label="仓库" min-width="150" />
                                <el-table-column prop="warehousingNum" label="入库数量" width="110" align="right" />
                                <el-table-column label="入库金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.warehousingMoney) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="documentCreator" label="制单人" width="120" />
                                <el-table-column prop="reviewerPeople" label="审核人" width="120" />
                            </el-table>
                            <el-empty
                                v-else-if="!inboundLoading"
                                description="暂无入库记录"
                            />
                        </div>
                    </el-tab-pane>                  
                </el-tabs>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { DocumentCopy } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import myaxios from '@/http/MyAxios';

const route = useRoute();
const router = useRouter();

// 当前激活的标签页
const activeTab = ref('other');

const info = reactive({
    supplierId: route.query.supplierId || '',
    supplierCode: '',
    supplierName: '',
    supplierTypeId: '',
    supplierTypeName: '',
    contact: '',
    contactNumber: '',
    supplierEmail: '',
    industryId: '',
    industryName: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    supplierStatus: '',
    supplierAddress: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    remarks: '',
    createor: '',
    createrTime: '',
    updator: '',
    updateTime: '',
})

const pickFirst = (data: Record<string, any>, keys: string[], defaultValue: any = '') => {
    if (!data) return defaultValue
    for (const key of keys) {
        const value = data?.[key]
        if (value !== undefined && value !== null && value !== '') {
            return value
        }
    }
    return defaultValue
}

// 附件列表
const attachments = ref<Array<{ name: string; url: string }>>([])

// 自定义字段
const customFields = ref<Array<{ label: string; value: string }>>([])

// 记录数据
const purchaseRecords = ref<any[]>([])
const outboundRecords = ref<any[]>([])
const inboundRecords = ref<any[]>([])
const industryOptions = ref<any[]>([])
const supplierTypeOptions = ref<any[]>([])
const warehousingTypeOptions = ref<any[]>([])
const purchaseLoading = ref(false)
const outboundLoading = ref(false)
const inboundLoading = ref(false)
const purchaseLoaded = ref(false)
const outboundLoaded = ref(false)
const inboundLoaded = ref(false)

// 格式化日期
const formatDate = (date: any) => {
    if (!date) return '-';
    try {
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
    } catch (error) {
        return date;
    }
}

const formatAmount = (amount?: number | string) => {
    if (amount === undefined || amount === null || amount === '') return '0.00'
    const num = Number(amount)
    if (Number.isNaN(num)) return '0.00'
    return num.toFixed(2)
}

const industryMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    industryOptions.value.forEach((item: any) => {
        const id = item?.industryId ?? item?.dictionaryId
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.industryName ?? item?.dictionaryName ?? ''
        }
    })
    return map
})

const supplierTypeMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    supplierTypeOptions.value.forEach((item: any) => {
        const id = item?.supplierTypeId ?? item?.dictionaryId
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.supplierTypeName ?? item?.dictionaryName ?? ''
        }
    })
    return map
})

const warehousingTypeMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    warehousingTypeOptions.value.forEach((item: any) => {
        const id = item?.warehousingTypeId ?? item?.id
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.warehousingName ?? item?.warehousingTypeName ?? item?.name ?? ''
        }
    })
    return map
})

// 复制功能
const handleCopy = async () => {
    try {
        const textToCopy = `${info.supplierName || ''} ${info.supplierCode || ''}`.trim();
        if (!textToCopy) {
            ElMessage.warning('暂无可复制内容')
            return
        }
        await navigator.clipboard.writeText(textToCopy);
        ElMessage.success('复制成功');
    } catch (error) {
        ElMessage.error('复制失败，请手动复制');
        console.error('复制失败:', error);
    }
};

// 编辑功能
const handleEdit = () => {
    router.push({
        path: '/UpdateSupplier',
        query: { supplierId: String(info.supplierId ?? '') }
    });
}

// 删除功能
const handleDelete = () => {
    ElMessageBox.confirm(
        '确认删除该供应商吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 调用删除接口
            myaxios.put(`/api/Supplier/DeleteSupplier?supplierid=${info.supplierId}`)
                .then((res: any) => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message);
                        router.push('/GetSupplier')
                        router.back();
                    } else {
                        ElMessage.error(res.data.message);
                    }
                })
                .catch((error: any) => {
                    ElMessage.error('删除失败');
                    console.error('删除失败:', error);
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}

// 停用功能
const handleDisable = () => {
    ElMessageBox.confirm(
        '确认停用该供应商吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            ElMessage.success('停用功能待实现');
            // 调用停用接口
        })
        .catch(() => {
            ElMessage.info('已取消停用');
        });
}

// 打印功能
const handlePrint = () => {
    window.print();
}

const supplierId = () => String(route.query.supplierId || info.supplierId || '')

const isRootDictionary = (item: any) =>
    !item?.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item?.dictionaryName || '').toLowerCase()
    const code = (item?.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const params = { Pageindex: 1, PageSize: 1000 }
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const list = res.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 },
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 },
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryOptions = async () => {
    try {
        const directRes = await myaxios.get('api/Supplier/GetIndustry')
        if (Array.isArray(directRes.data?.data) && directRes.data.data.length > 0) {
            industryOptions.value = directRes.data.data
            return
        }
    } catch (err) {
        console.warn('通过 Supplier/GetIndustry 获取行业失败，尝试字典接口', err)
    }

    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    industryOptions.value = children.map((item: any) => ({
        industryId: item.dictionaryId,
        industryName: item.dictionaryName,
    }))
}

const loadSupplierTypeOptions = async () => {
    const parentId = await findDictionaryParentId(['供应商分类', '供应商类型'], ['suppliertype', 'supplier_type'])
    const children = await fetchDictionaryChildren(parentId)
    supplierTypeOptions.value = children.map((item: any) => ({
        supplierTypeId: item.dictionaryId,
        supplierTypeName: item.dictionaryName,
    }))
}

const loadWarehousingTypeOptions = async () => {
    try {
        const res = await myaxios.get('/api/Warehousing/GetWarehousingType')
        if (res.data?.success || res.data?.code === 200) {
            warehousingTypeOptions.value = res.data?.data || []
        }
    } catch (error) {
        console.warn('获取入库类型失败', error)
    }
}

const resolveSupplierMeta = () => {
    const industryKey = info.industryId ? String(info.industryId) : ''
    if (!info.industryName && industryKey) {
        info.industryName = industryMap.value[industryKey] || info.industryName
    }
    const supplierTypeKey = info.supplierTypeId ? String(info.supplierTypeId) : ''
    if (!info.supplierTypeName && supplierTypeKey) {
        info.supplierTypeName = supplierTypeMap.value[supplierTypeKey] || info.supplierTypeName
    }
}

// 加载供应商详情
const loadSupplierDetail = async () => {
    const id = supplierId()
    if (!id) {
        ElMessage.error('缺少supplierId')
        router.push('/GetSupplier')
        return
    }
    try {
        const res = await myaxios.get('/api/Supplier/GetSupplierById', {
            params: { supplierId: id },
        })
        if (res.data?.code === 200) {
            const data = res.data.data || {}
            const industryIdValue = pickFirst(data, ['industryId', 'industry', 'industryCode']) || route.query.industryId
            const supplierTypeIdValue = pickFirst(data, ['supplierTypeId', 'supplierCategoryId', 'categoryId']) || route.query.supplierTypeId
            Object.assign(info, {
                supplierId: pickFirst(data, ['supplierId', 'SupplierId', 'id'], id),
                supplierCode: pickFirst(data, ['supplierCode', 'supplierNo', 'code']) || route.query.supplierCode,
                supplierName: pickFirst(data, ['supplierName', 'name']) || route.query.supplierName,
                supplierTypeId: supplierTypeIdValue || '',
                supplierTypeName:
                    pickFirst(data, ['supplierTypeName', 'supplierCategoryName', 'categoryName']) ||
                    (supplierTypeIdValue ? supplierTypeMap.value[String(supplierTypeIdValue)] : '') ||
                    (route.query.supplierTypeName as string) ||
                    '',
                contact: pickFirst(data, ['contact', 'contactName', 'linkMan']) || route.query.contact,
                contactNumber: pickFirst(data, ['contactNumber', 'contactPhone', 'phone']) || route.query.contactNumber,
                supplierEmail: pickFirst(data, ['supplierEmail', 'email']) || route.query.supplierEmail,
                industryId: industryIdValue || '',
                industryName:
                    pickFirst(data, ['industryName', 'belongIndustryName', 'industry']) ||
                    (industryIdValue ? industryMap.value[String(industryIdValue)] : '') ||
                    (route.query.industryName as string) ||
                    '',
                organizationId: pickFirst(data, ['organizationId', 'orgId']) || route.query.organizationId,
                organizationName: pickFirst(data, ['organizationName', 'departmentName']) || route.query.organizationName,
                userId: pickFirst(data, ['userId', 'handlerId']) || route.query.userId,
                userName: pickFirst(data, ['userName', 'handlerName', 'purchaseLeader']) || route.query.userName,
                supplierStatus: pickFirst(data, ['supplierStatus', 'status']) || route.query.supplierStatus,
                supplierAddress: pickFirst(data, ['supplierAddress', 'address']) || route.query.supplierAddress,
                financeName: pickFirst(data, ['financeName', 'accountName']),
                taxpayerNumber: pickFirst(data, ['taxpayerNumber', 'taxNumber']),
                bankAccount: pickFirst(data, ['bankAccount', 'accountNumber']),
                accountBank: pickFirst(data, ['accountBank', 'bankName']),
                bankAddress: pickFirst(data, ['bankAddress']),
                remarks: pickFirst(data, ['remarks', 'remark', 'note']),
                createor: pickFirst(data, ['createor', 'creator', 'createUser']),
                createrTime: pickFirst(data, ['createrTime', 'createTime']),
                updator: pickFirst(data, ['updator', 'updateUser']),
                updateTime: pickFirst(data, ['updateTime', 'updateDate', 'modifiedTime']),
            })
            resolveSupplierMeta()
            attachments.value = Array.isArray(data.files)
                ? data.files.map((file: any) => ({
                    name: file.fileName || file.name,
                    url: file.fileUrl || file.url,
                }))
                : []
            customFields.value = Array.isArray(data.customFields)
                ? data.customFields.map((item: any) => ({
                    label: item.label || item.fieldName || '自定义字段',
                    value: item.value || item.fieldValue || '',
                }))
                : []
        }
    } catch (error) {
        console.error('获取供应商详情失败:', error)
        ElMessage.error('获取供应商详情失败')
    }
}

const getPurchaseStatusText = (status: number | string) => {
    const map: Record<string, string> = {
        '0': '草稿',
        '1': '待审核',
        '2': '驳回',
        '3': '未出库',
        '4': '部分出库',
        '5': '已完成',
        '6': '已关闭',
    }
    return map[String(status)] || '未知'
}

const getPurchaseStatusTag = (status: number | string) => {
    const map: Record<string, string> = {
        '0': 'info',
        '1': 'warning',
        '2': 'danger',
        '3': 'info',
        '4': 'warning',
        '5': 'success',
        '6': 'danger',
    }
    return map[String(status)] || 'info'
}

const PURCHASE_RETURN_STATUS = [
    { value: 0, label: '草稿', tagType: 'info' },
    { value: 1, label: '待审核', tagType: 'warning' },
    { value: 2, label: '驳回', tagType: 'danger' },
    { value: 3, label: '未出库', tagType: 'info' },
    { value: 4, label: '部分出库', tagType: 'warning' },
    { value: 5, label: '已完成', tagType: 'success' },
    { value: 6, label: '已关闭', tagType: 'danger' },
]

const getReturnStatusText = (status: number | string) => {
    const option = PURCHASE_RETURN_STATUS.find(item => Number(item.value) === Number(status))
    return option?.label || '未知'
}

const getReturnStatusTag = (status: number | string) => {
    const option = PURCHASE_RETURN_STATUS.find(item => Number(item.value) === Number(status))
    return option?.tagType || 'info'
}

const extractList = (payload: any) => {
    if (!payload) return []
    if (Array.isArray(payload)) return payload
    if (Array.isArray(payload.data)) return payload.data
    if (Array.isArray(payload.records)) return payload.records
    if (Array.isArray(payload.list)) return payload.list
    if (Array.isArray(payload.items)) return payload.items
    return []
}

const fetchPurchaseRecords = async () => {
    if (!supplierId()) return
    purchaseLoading.value = true
    try {
        const res = await myaxios.get('/api/StockinGoods/GetStockinGoods', {
            params: {
                supplierId: supplierId(),
                pageindex: 1,
                pagesize: 20,
            },
        })
        const dataSection = res.data?.data || res.data || {}
        const list = extractList(dataSection)
        purchaseRecords.value = list
        purchaseLoaded.value = true
    } catch (error) {
        console.error('获取进货记录失败:', error)
        ElMessage.error('获取进货记录失败')
    } finally {
        purchaseLoading.value = false
    }
}

const fetchOutboundRecords = async () => {
    if (!supplierId()) return
    outboundLoading.value = true
    try {
        const res = await myaxios.get('/api/GoodsReturns/GetGoodsReturns', {
            params: {
                supplierId: supplierId(),
                pageindex: 1,
                pagesize: 20,
            },
        })
        const dataSection = res.data?.data || res.data || {}
        const list = extractList(dataSection)
        outboundRecords.value = list
        outboundLoaded.value = true
    } catch (error) {
        console.error('获取出库记录失败:', error)
        ElMessage.error('获取出库记录失败')
    } finally {
        outboundLoading.value = false
    }
}

const fetchInboundRecords = async () => {
    if (!supplierId()) return
    inboundLoading.value = true
    try {
        const res = await myaxios.get('/api/Warehousing/GetWarehousing', {
            params: {
                supplierId: supplierId(),
                pageindex: 1,
                pagesize: 20,
            },
        })
        const dataSection = res.data?.data || res.data || {}
        const list = extractList(dataSection)
        inboundRecords.value = list.map((item: any) => {
            const typeId = pickFirst(item, ['warehousingTypeId', 'typeId'])
            const typeName =
                pickFirst(item, ['warehousingTypeName', 'warehousingType', 'typeName']) ||
                (typeId ? warehousingTypeMap.value[String(typeId)] : '')
            return {
                warehousingCode: pickFirst(item, ['warehousingCode', 'warehousingNo', 'warehousingGoodsNo', 'inboundNo']),
                warehousingTypeId: typeId,
                warehousingTypeName: typeName,
                storageDate: pickFirst(item, ['storageDate', 'warehousingDate', 'inboundDate']),
                warehouseName: pickFirst(item, ['warehouseName', 'warehouse']),
                warehousingNum: Number(pickFirst(item, ['warehousingNum', 'inboundQuantity', 'quantity'], 0)),
                warehousingMoney: Number(pickFirst(item, ['warehousingMoney', 'amount', 'totalAmount'], 0)),
                documentCreator: pickFirst(item, ['documentCreator', 'createor', 'creator', 'maker']),
                reviewerPeople: pickFirst(item, ['reviewerPeople', 'auditor', 'reviewer']),
            }
        })
        inboundLoaded.value = true
    } catch (error) {
        console.error('获取入库记录失败:', error)
        ElMessage.error('获取入库记录失败')
    } finally {
        inboundLoading.value = false
    }
}

watch(activeTab, (tab) => {
    if (tab === 'purchase' && !purchaseLoaded.value) {
        fetchPurchaseRecords()
    } else if (tab === 'outbound' && !outboundLoaded.value) {
        fetchOutboundRecords()
    } else if (tab === 'inbound' && !inboundLoaded.value) {
        fetchInboundRecords()
    }
})

watch(
    () => info.supplierId,
    (id) => {
        if (!id) return
        if (activeTab.value === 'purchase' && !purchaseLoaded.value) {
            fetchPurchaseRecords()
        } else if (activeTab.value === 'outbound' && !outboundLoaded.value) {
            fetchOutboundRecords()
        } else if (activeTab.value === 'inbound' && !inboundLoaded.value) {
            fetchInboundRecords()
        }
    },
)

watch([industryOptions, supplierTypeOptions], () => {
    resolveSupplierMeta()
})

watch(warehousingTypeOptions, () => {
    if (!inboundRecords.value.length) return
    inboundRecords.value = inboundRecords.value.map((item) => ({
        ...item,
        warehousingTypeName:
            item.warehousingTypeName ||
            (item.warehousingTypeId ? warehousingTypeMap.value[String(item.warehousingTypeId)] : ''),
    }))
})

onMounted(async () => {
    await Promise.all([
        loadIndustryOptions(),
        loadSupplierTypeOptions(),
        loadWarehousingTypeOptions(),
    ])
    await loadSupplierDetail()
    if (activeTab.value === 'purchase') {
        fetchPurchaseRecords()
    }
})
</script>

<style scoped>
.detail-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.detail-card {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0;
    border-radius: 8px;
    overflow: hidden;
}

/* 顶部标题和操作区域 */
.header-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24px 24px 20px;
    border-bottom: 1px solid #e4e7ed;
    background-color: #fff;
}

.title-area {
    display: flex;
    align-items: center;
    flex: 1;
}

.title {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin: 0;
    margin-right: 12px;
}

.copy-icon {
    cursor: pointer;
    color: #606266;
    font-size: 20px;
    transition: color 0.2s;
}

.copy-icon:hover {
    color: #409eff;
}

.action-area {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 12px;
}

.status-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

/* 基本信息卡片 */
.info-card {
    padding: 24px;
    background-color: #fff;
}

.info-row {
    margin-top: 16px;
}

.audit-row {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 2px solid #e4e7ed;
}

.info-value {
    color: #303133;
    font-size: 14px;
}

/* 标签页区域 */
.tabs-section {
    padding: 0 24px 24px;
    background-color: #fff;
}

.detail-tabs {
    margin-top: 20px;
}

.tab-content {
    padding: 20px 0;
    min-height: 300px;
}

.section-block {
    margin-bottom: 32px;
}

.section-block:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #409eff;
}

.attachment-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.file-link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.2s;
}

.file-link:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
}

.empty-text {
    color: #909399;
    font-size: 14px;
    padding: 20px 0;
    text-align: center;
}

/* Element Plus 样式覆盖 */
:deep(.el-descriptions__label) {
    font-weight: 500;
    background-color: #fafafa;
    width: 120px;
    color: #606266;
}

:deep(.el-descriptions__content) {
    background-color: #fff;
    color: #303133;
}

:deep(.el-tabs__header) {
    margin: 0 0 20px 0;
}

:deep(.el-tabs__item) {
    font-size: 14px;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
}

:deep(.el-tabs__item.is-active) {
    color: #409eff;
    font-weight: 500;
}

:deep(.el-descriptions__table) {
    border-collapse: separate;
    border-spacing: 0;
}

:deep(.el-descriptions__cell) {
    padding: 12px 16px;
}

/* 打印样式 */
@media print {
    .detail-container {
        background-color: #fff;
        padding: 0;
    }

    .action-area {
        display: none;
    }

    .detail-tabs {
        display: none;
    }

    .tabs-section {
        display: none;
    }
}
</style>
